package com.steven.im.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.base.Constant;
import com.steven.im.myinterface.JsInterface;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.TitleBuilder;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by Steven on 2018/6/27.
 * 显示网页信息
 */
public class WebActivity extends BaseActivity {
    @BindView(R.id.myProgressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.webView)
    WebView webView;
    private String url;
    private String title;
    private String referer;//上一个页面来源
    private String my_jessionId = "";

    @SuppressLint("SetJavaScriptEnabled")
    private void setWebView() {
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        referer = getIntent().getStringExtra("referer");
        WebSettings settings = webView.getSettings();

        //WebView加载web资源
        int screenDensity = getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
            default:
                break;
        }
        settings.setDefaultZoom(zoomDensity);

        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 不使用缓存
        webView.addJavascriptInterface(new JsInterface(WebActivity.this), "android");
        String ua = webView.getSettings().getUserAgentString();
        settings.setUserAgentString(ua + "android/ts");
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDisplayZoomControls(false);//隐藏Zoom缩放按钮
        //解除数据阻止
        settings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            settings.setMixedContentMode(2);
        }
        Map<String, String> map = new HashMap<>();
        my_jessionId = SPUtils.get(App.getContext(), Constant.CommonInfo.JSESSIONID, "") + "";
        map.put("jsessionid", my_jessionId);

//        webView.loadUrl(url, map);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                new TitleBuilder(WebActivity.this).setTitleText(title)
                        .setLeftIcoListening(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (!TextUtils.isEmpty(referer) && "AdvertActivity".equals(referer)) {
                                    startActivity(new Intent(WebActivity.this, MainActivity.class));
                                }
                                finish();
                            }
                        });
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    if (mProgressBar.getVisibility() == View.GONE)
                        mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //网页在webView中打开
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {//安卓5.0的加载方法
                    view.loadUrl(request.toString());
                } else {//5.0以上的加载方法
                    view.loadUrl(request.getUrl().toString());
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受所有网站的证书
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        webView.loadUrl(url, map);
    }

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
        setWebView();
    }

    @Override
    public void initData() {
//        new TitleBuilder(this).setTitleText(title)
//                .setLeftIcoListening(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        if (!TextUtils.isEmpty(referer) && "AdvertActivity".equals(referer)) {
//                            startActivity(new Intent(WebActivity.this, MainActivity.class));
//                        }
//                        finish();
//                    }
//                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        String sessionId = SPUtils.get(App.getContext(), Constant.CommonInfo.JSESSIONID, "") + "";
        if (!sessionId.equals(my_jessionId)) {
            Map<String, String> map = new HashMap<>();
            my_jessionId = SPUtils.get(App.getContext(), Constant.CommonInfo.JSESSIONID, "") + "";
            map.put("jsessionid", my_jessionId);
            webView.loadUrl(url, map);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!TextUtils.isEmpty(referer) && "AdvertActivity".equals(referer)) {
                startActivity(new Intent(WebActivity.this, MainActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
